package cc.magicjson.jpa.datasouce.write.service;


import cc.magicjson.jpa.datasouce.entity.Users;
import cc.magicjson.jpa.datasouce.write.repositories.PrimaryUserRepository;
import cc.magicjson.jpa.datasouce.write.repositories.SecondaryUserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class UserService {


    private final PrimaryUserRepository primaryUserRepository;

    private final SecondaryUserRepository secondaryUserRepository;

    public UserService(PrimaryUserRepository primaryUserRepository, SecondaryUserRepository secondaryUserRepository) {
        this.primaryUserRepository = primaryUserRepository;
        this.secondaryUserRepository = secondaryUserRepository;
    }

    public List<Users> findUserById(Long id) {
         return Arrays.asList(primaryUserRepository.findById(id).orElse(null)
             , secondaryUserRepository.findById(id).orElse(null));
    }

    @Transactional
    public void saveUser(Users users) {
        // 保存到第一个数据源
        primaryUserRepository.save(users);

        // 从第一个数据源中刷新对象
        primaryUserRepository.flush();

        // 获取 ID
        Long id = users.getId();

        // 从第一个数据源获取对象
        Users fetchedUser = primaryUserRepository.findById(id).orElse(null);

        // 保存到第二个数据源
        secondaryUserRepository.save(fetchedUser);
    }
}
